﻿import type { RequestOptions } from '@@/plugin-request/request';
import type { RequestConfig } from '@umijs/max';
import { message } from 'antd';

enum StatusType {
  StatusErr = "error",
  StatusOk = "ok"
}

interface ResponseStructure {
  status: string;
  data: any;
  message: string;
}

/**
 * @name 错误处理
 * pro 自带的错误处理， 可以在这里做自己的改动
 * @doc https://umijs.org/docs/max/request#配置
 */
export const errorConfig: RequestConfig = {
  // 错误处理： umi@3 的错误处理方案。
  errorConfig: {
    // 错误抛出
    errorThrower: (res) => {
      const { status, message } =
        res as unknown as ResponseStructure;
      if (status == StatusType.StatusErr) {
        throw new Error(message); // 抛出自制的错误
      }
    },
    // 错误接收及处理
    errorHandler: (error: any, opts: any) => {
      if (opts?.skipErrorHandler) throw error;

      // 前端中断请求
      if (error?.code == "ERR_CANCELED") {
        return 
      }

      message.error(error?.response?.data?.message);
      if (error?.response?.status == 401) {
        const url = new URL("/user/login", window.location.origin);
        url.searchParams.set('redirect', location.pathname);
        window.location.href = url.toString()
      }
    }
  },

  // 请求拦截器
  requestInterceptors: [
    (config: RequestOptions) => {
      // 拦截请求配置，进行个性化处理。
      const url = config?.url;
      return { ...config, url, withCredentials: true };
    },
  ],

  // 响应拦截器
  responseInterceptors: [
    (response) => response
  ],
};
